package com.minisoft.pool;

import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import cn.hutool.db.Page;
import cn.hutool.db.PageResult;
import com.minisoft.entity.OpportunityDetailsXcxVo;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;

/**
 * @author JueSu
 * @description: TODO
 * @date 2023/7/4 17:09
 */
@Slf4j
public class FlushAnswerTime {

    public static String DB_CENTER = "center-pro";

//    public static String DB_CENTER = "center-dev";
    private static long beginTime = System.currentTimeMillis();;
    private static AtomicLong totalNum = new AtomicLong(0);
    public static void main(String[] args) throws SQLException {
        ExecutorService service = ThreadUtil.newExecutor(1);
        service.execute(new FlushTask());
    }

    static class FlushTask implements Runnable{

        @SneakyThrows
        @Override
        public void run() {
            Page page = new Page();
            page.setPageSize(1000);
            int pageNum = 0;//从第0页开始
            int total = 0;
            PageResult<Entity> pageResult = getPageResult(pageNum,page);
            long startTime = System.currentTimeMillis();
            while (!pageResult.isEmpty()) {
                List<Object[]> params = pageResult.stream().map(item -> {
                    Date date = new Date(item.getDate("answer_time").getTime()*1000);
                    return new Object[]{date,item.getLong("id")};
                }).collect(Collectors.toList());
                total+=pageResult.size();
                Db.use(DB_CENTER).executeBatch("update cp_allocation_details set answer_time = ? where id = ?",params);
                log.info("更新第{}页客户，已更新总量：{}",pageNum,total);
                pageNum++;
                pageResult = getPageResult(pageNum,page);
            }
            long endTime = System.currentTimeMillis();
            int second = (int) (endTime-startTime)/1000;
            log.info("耗时：{}s,全局总耗时：{}s，全局总人数：{}",second,(endTime-beginTime)/1000,totalNum.addAndGet(total));
        }

        private PageResult<Entity> getPageResult(int pageNum, Page page) throws SQLException {
            page.setPageNumber(0);//因为只返回未更新的，所以只拿第0页就好
            PageResult<Entity> pageResult = Db.use(DB_CENTER).page("select cad2.id,cad2.answer_time  from cp_allocation_details cad2 where cad2.answer_time < '2000-01-20 21:03:52'", page);
            return pageResult;
        }

    }

}
